package ch.zhaw.hgc.controllers;

import java.io.ByteArrayInputStream;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import ch.zhaw.hgc.entities.Recipe;
import ch.zhaw.hgc.services.IRecipeService;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * @author Francesco Gallo Description: Provides the basic functionality to show
 *         a detail view of a recipe
 */
@Controller
@RequestMapping("/recipedetail")
public class RecipeDetailController {

	/**
	 * Logger Object
	 */
	private static final Logger logger = Logger
			.getLogger(RecipeDetailController.class);

	@Autowired
	private IRecipeService recipeService;

	/**
	 * This method returns a Recipe object according the defined id.
	 * 
	 * @param id
	 *            Id of the Recipe to show
	 * @return Recipe Object to show
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView get(@RequestParam("id") long id) {
		Key key = KeyFactory.createKey(Recipe.class.getSimpleName(), id);
		ModelAndView mav = new ModelAndView("recipedetail");
		Recipe recipe = recipeService.findByKey(key);
		mav.addObject("image",
				new ByteArrayInputStream(recipe.getRecipeImage()));
		mav.addObject("recipe", recipeService.findByKey(key));
		logger.info("Passed get() method in controller...");
		return mav;
	}

	@RequestMapping(value = "image", method = RequestMethod.GET)
	public ResponseEntity<byte[]> getImage(@RequestParam("id") long id) {
		Key key = KeyFactory.createKey(Recipe.class.getSimpleName(), id);
		Recipe recipe = recipeService.findByKey(key);

		logger.info("Passed get() method in controller...");
		HttpHeaders headers = new HttpHeaders();

		headers.setContentType(MediaType.valueOf("image/gif"));
		headers.setContentLength(recipe.getRecipeImage().length);

		//headers.add("Content-Disposition", "filename=test.gif");

		return new ResponseEntity<byte[]>(recipe.getRecipeImage(), headers,
				HttpStatus.OK);

	}

}
